import math as m
import random
import chaosLib as chaos
import Sboxlib as sbox
import numpy as np
import scipy
import cv2 as cv
import encImg as enc
import drawChaos
import facedeteDemo as FD
import cvlib as cl
import  decImg
from matplotlib import pyplot as plt


if __name__ == '__main__':
    # encrypt start
    print("A multimedia encryption scheme for sensitive data classification based on YOLO Demo")
    # 图像路径
    data_root = r'E:\dataset\VOC\VOCdevkit\VOC2007\JPEGImages\000021.jpg'
    # 1. 读取图像
    img = enc.Dataloader(data_root)

    # show plaintext image

    # cv.imshow('Plaintext image', img)
    # cv.waitKey(0)

    # 2. 目标识别
    faces, confidences = cl.detect_face(img)
    # 可视化
    img_result = FD.show_detection(img.copy(), faces)
    FD.show_img_with_matplotlib(img_result, "detector: " + str(len(faces)), 1)
    plt.show()

    # 3. iterate chaos function
    # 确定循环次数
    [l, h, w] = img.shape
    times = l * h

    prng_arr = chaos._2D_sine_logistic(4, 3, 0.321, 0.3293, times+1)

    # 4. generate key
    user_key = '3daojfdioajfodajfodajoi' + str(faces) + str(confidences)
    key = enc.keyGen(user_key, str(faces))
    print(faces)

    # 5. sample chaos sequences
    prng = enc.sample(prng_arr, key)

    # 6. diffusion process
    img_diff_B = enc.enc_diffusion(img[:, :, 0], prng[0, :].reshape(l, h))
    img_diff_G = enc.enc_diffusion(img[:, :, 1], prng[1, :].reshape(l, h))
    img_diff_R = enc.enc_diffusion(img[:, :, 2], prng[0, :].reshape(l, h))

    # 7. confuse process
    img_confuse_B = enc.enc_confuse(img_diff_B, 10)
    img_confuse_G = enc.enc_confuse(img_diff_G, 10)
    img_confuse_R = enc.enc_confuse(img_diff_R, 10)

    # encrypt end
    cipher = np.uint8(np.zeros([l,h,w]))
    cipher[:, :, 0] = img_confuse_B
    cipher[:, :, 1] = img_confuse_G
    cipher[:, :, 2] = img_confuse_R

    # show cipher image
    cv.imshow('cipher', cipher)
    cv.imwrite('../experiment/enc_result/cipher.jpg', cipher)
    cv.waitKey(0)

    # cv.destroyWindow('cipher')
    print(cipher)

    # write cipher image

    np.save(r'../experiment/enc_result/cipher.npy', cipher)





    #decrypte image

    plain = decImg.decryptImage(cipher, prng)

    # cipher = cv.imread('../experiment/enc_result/noise_cipher.jpg')
    # plain = decImg.decryptImage(cipher, prng)
    # show cipher image
    cv.imshow('plain', plain)
    cv.imwrite('../experiment/enc_result/plain.jpg', plain)
    cv.waitKey(0)

    # cv.destroyWindow('cipher')
    print(plain)

    # write cipher image

    np.save(r'../experiment/enc_result/plain.npy', plain)

